import { NavBar, Button, Input, Avatar, Toast } from "antd-mobile";
import { AudioOutline, SendOutline } from "antd-mobile-icons";
import { useState, useRef, useEffect } from "react";
import { useNavigate } from "react-router-dom";
// 直接使用 fetch 请求 Moonshot API
import "./ai.css";

interface Message {
  id: string;
  type: "user" | "bot";
  content: string;
  timestamp: Date;
}

function AI() {
  const navigate = useNavigate();
  const [inputValue, setInputValue] = useState("");
  const [messages, setMessages] = useState<Message[]>([
    {
      id: "1",
      type: "bot",
      content:
        "HI,我是专属智能客服,土豆炖蘑菇 遇到问题,请尽管问我,我来陪你解答",
      timestamp: new Date(),
    },
  ]);
  const [isLoading, setIsLoading] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 猜你想问的问题列表
  const suggestedQuestions = [
    "如何绑定电子就诊卡?",
    "门诊挂号如何操作?",
    "处方能在手机上缴费吗?",
    "门诊挂号能使用医保支付吗?",
    "住院预交金能给亲友充值吗?",
    "如何在手机上进行门诊挂号退费?",
  ];

  // 猜你想做的功能列表
  const suggestedActions = [
    { name: "门诊挂号", action: "registration" },
    { name: "门诊缴费", action: "payment" },
    { name: "门诊报告", action: "report" },
  ];

  // 处理AI回复
  const handleAIResponse = async (userMessage: string) => {
    try {
      setIsLoading(true);
      console.log('🤖 开始处理AI回复:', userMessage);
      
      // 添加一个临时的加载消息
      const loadingMessage: Message = {
        id: `loading-${Date.now()}`,
        type: "bot",
        content: "正在思考中...",
        timestamp: new Date(),
      };
      setMessages((prev) => [...prev, loadingMessage]);
      
      // 构建聊天消息历史
      const chatHistory = [
        {
          role: 'system',
          content: '你是一个专业的医疗智能客服助手，专门帮助用户解答关于医院服务、挂号、缴费、报告查询等问题。请用友好、专业的语气回答用户的问题。'
        },
        ...messages.slice(-10).map(msg => ({
          role: msg.type === 'user' ? 'user' : 'assistant',
          content: msg.content
        })),
        {
          role: 'user',
          content: userMessage
        }
      ];

      console.log('📝 发送聊天历史:', chatHistory);

      // 使用 fetch 直接请求 Moonshot API
      const response = await fetch('https://api.moonshot.cn/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer sk-UZr1pGehZlVSBzEb65JyBdLVR5YYahr4DaAohDGUUYAQwTxI',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: 'moonshot-v1-8k',
          messages: chatHistory,
          temperature: 0.7,
          max_tokens: 1000,
        }),
      });

      console.log('📡 API响应状态:', response.status);

      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
      }

      const data = await response.json();
      console.log('✅ API响应数据:', data);

      // 获取AI回复内容
      const aiContent = data.choices?.[0]?.message?.content || '抱歉，我暂时无法回答您的问题，请稍后再试。';
      console.log('💬 AI回复内容:', aiContent);
      
      // 移除加载消息并添加AI回复
      setMessages((prev) => {
        const filteredMessages = prev.filter(msg => !msg.id.startsWith('loading-'));
        const botReply: Message = {
          id: (Date.now() + 1).toString(),
          type: "bot",
          content: aiContent,
          timestamp: new Date(),
        };
        return [...filteredMessages, botReply];
      });
      console.log('✅ 消息已添加到聊天记录');
    } catch (error) {
      console.error('❌ AI回复失败:', error);
      Toast.show('AI服务暂时不可用，请稍后再试');
      
      // 降级到模拟回复，移除加载消息
      setMessages((prev) => {
        const filteredMessages = prev.filter(msg => !msg.id.startsWith('loading-'));
        const fallbackReply: Message = {
          id: (Date.now() + 1).toString(),
          type: "bot",
          content: "感谢您的咨询，我正在为您查询相关信息，请稍候...",
          timestamp: new Date(),
        };
        return [...filteredMessages, fallbackReply];
      });
    } finally {
      setIsLoading(false);
      console.log('🏁 AI回复处理完成');
    }
  };

  const handleQuestionClick = (question: string) => {
    const newMessage: Message = {
      id: Date.now().toString(),
      type: "user",
      content: question,
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, newMessage]);
    
    // 调用AI处理
    handleAIResponse(question);
  };

  const handleActionClick = (action: string) => {
    console.log("选择操作:", action);
    // 这里可以添加导航到相应页面的逻辑
  };

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 调试信息
  useEffect(() => {
    console.log('🔧 AI页面已加载');
    console.log('📊 当前消息数量:', messages.length);
    console.log('⏳ 加载状态:', isLoading);
  }, [messages.length, isLoading]);

  const handleSendMessage = () => {
    if (inputValue.trim() && !isLoading) {
      const userMessage = inputValue.trim();
      const newMessage: Message = {
        id: Date.now().toString(),
        type: "user",
        content: userMessage,
        timestamp: new Date(),
      };

      setMessages((prev) => [...prev, newMessage]);
      setInputValue("");

      // 调用AI处理
      handleAIResponse(userMessage);
    }
  };

  const handleVoiceInput = () => {
    console.log("语音输入");
    // 这里可以添加语音输入的逻辑
    
  };

  return (
    <div className="ai-container">
      {/* 顶部导航栏 */}
      <NavBar onBack={() => navigate(-1)} className="ai-navbar">
        智能客服
      </NavBar>

      {/* 猜你想问 - 固定在顶部 */}
      <div className="fixed-suggested-section">
        <div className="section-header">
          <h3 className="section-title">猜你想问</h3>
          <Button
            size="mini"
            className="change-batch-btn"
            onClick={() => console.log("换一批")}
          >
            换一批
          
          </Button>
        </div>
        
        <div className="questions-list">
          {suggestedQuestions.map((question, index) => (
            <div
              key={index}
              className="question-item"
              onClick={() => handleQuestionClick(question)}
            >
              <span className="question-number">{index + 1}</span>
              <span className="question-text">{question}</span>
            </div>
          ))}
        </div>
         {/* 猜你想做 */}
        <div className="suggested-section">
          <div className="section-header">
            <h3 className="section-title">猜你想做</h3>
          </div>
          <div className="actions-list">
            {suggestedActions.map((action, index) => (
              <Button
                key={index}
                className="action-btn"
                onClick={() => handleActionClick(action.action)}
              >
                {action.name}
              </Button>
            ))}
          </div>
        </div>
      </div>

      {/* 聊天内容区域 */}
      <div className="chat-content">
        {/* 消息列表 */}
        {messages.map((message) => (
          <div
            key={message.id}
            className={`chat-message ${
              message.type === "user" ? "user-message" : "bot-message"
            }`}
          >
            <div className="message-avatar">
              {message.type === "user" ? (
                <Avatar
                  src="👤"
                  style={{ "--size": "40px", fontSize: "20px" }}
                />
              ) : (
                <div className="bot-icon">🤖</div>
              )}
            </div>
            <div className="message-bubble">
              <div className="message-text">
                {message.content}
                {message.id.startsWith('loading-') && (
                  <div className="loading-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                )}
              </div>
            </div>
          </div>
        ))}
        <div ref={messagesEndRef} />

       
      </div>

      {/* 底部输入区域 */}
      <div className="input-area">
        {isLoading && (
          <div className="loading-status">
            <div className="loading-text">
              <span className="loading-icon">🤖</span>
              AI正在思考中,请稍候...
            </div>
          </div>
        )}
        <div className="input-container">
          <Button className="voice-btn" onClick={handleVoiceInput} disabled={isLoading}>
            <AudioOutline fontSize={20} />
          </Button>
          <Input
            className="message-input"
            placeholder={isLoading ? "AI正在回复中..." : "请简述您的问题"}
            value={inputValue}
            onChange={setInputValue}
            onEnterPress={handleSendMessage}
            disabled={isLoading}
          />
          <Button
            className="send-btn"
            onClick={handleSendMessage}
            disabled={!inputValue.trim() || isLoading}
            loading={isLoading}
          >
            <SendOutline fontSize={20} />
          </Button>
        </div>
      </div>
    </div>
  );
}

export default AI;
